﻿using System;
using System.Collections.Generic;
using System.Text;

namespace UniversalApproach.Expands
{
    /// <summary>
    /// Json转换拓展
    /// </summary>
    public static class JsonExpand
    {
        /// <summary>
        /// 字符串使用<see cref="Newtonsoft.Json.JsonConvert.DeserializeObject"/>转换成泛类型
        /// </summary>
        /// <typeparam name="T">泛类型</typeparam>
        /// <param name="s">字符串</param>
        /// <returns>返回泛型类</returns>
        /// <exception cref="Exception"></exception>
        public static T ToObj<T>(this string s) where T : new()
        {
            if (string.IsNullOrEmpty(s))
                return default(T);

            try
            {
                var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(s);
                return obj;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 类型使用<see cref="Newtonsoft.Json.JsonConvert.SerializeObject"/>生成Json字符串
        /// </summary>
        /// <param name="o">类型</param>
        /// <returns>Json字符串<see cref="string"/></returns>
        public static string ToStr(this object o)
        {
            if (o == null)
                return string.Empty;

            try
            {
                var str = Newtonsoft.Json.JsonConvert.SerializeObject(o);
                return str;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
